package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.salesorder;

import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.citrus.cr.mn.order.center.forecastorder.ability.NormalPriceQueryUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crpricecenter.model.enums.PriceTypeEnum;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceMainRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceQueryRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomCreateLineRequest;
import com.epoch.app.mnordercenter.model.dto.SalesOrderBizCreateRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfStrategyCenter
 * @description: TODO
 * @date 2023/05/17 09:53
 * @version: 1.0
 */
@Service
@Order(4)
public class SalesOrderCreateBizAssembleOfCostCenter implements OrderBizAssemble<SalesOrderBizCreateRequest> {

    private static final Log log = Log.getLogger(SalesOrderCreateBizAssembleOfCostCenter.class);

    @Resource
    private NormalPriceQueryUtils normalPriceQueryUtils;

    @Override
    public Map<String, Object> query(SalesOrderBizCreateRequest salesOrderBizBatchCreateRequest) {
        Map<String, Object> result = Maps.newHashMap();

        result.put(String.format("costCenterCode_%s", "XA"), String.format("costCenterName_%s", "XA"));

        return result;
    }

    @Override
    public Map<String, Object> query(List<SalesOrderBizCreateRequest> orderBizCreateRequests) {
        return Maps.newHashMap();
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, SalesOrderBizCreateRequest createRequest) {

        Map<String, PolicyPriceQueryRequest> subOrderPriceMap = queryGoodsDetailPrice(createRequest);

        for (SalesOrderAtomCreateLineRequest orderDetail : createRequest.getOrderDetails()) {

            String priceLineKey = orderDetail.getProductCode() + "-" + orderDetail.getSalesUnitCode();
            PolicyPriceQueryRequest subOrderInfo = subOrderPriceMap.get(priceLineKey);
            if (Objects.isNull(subOrderInfo) || Objects.isNull(subOrderInfo.getUnitPrice()) || subOrderInfo.getUnitPrice() < 0L) {
//                return Result.fail(createRequest.getSourceOrderNo(), "OC-01-001-01-16-023", "价格格式错误");
                continue;
            }

            Long unitPrice = subOrderInfo.getUnitPrice();
            BigDecimal unitPriceNYC = new BigDecimal(String.valueOf(unitPrice)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            orderDetail.setUnitPrice(unitPriceNYC.toPlainString());

            if (StringUtils.isBlank(orderDetail.getProductQuantity())) {
                continue;
            }
            Long totalAmount = unitPrice * Long.parseLong(orderDetail.getProductQuantity());
            BigDecimal totalAmountNYC = new BigDecimal(String.valueOf(totalAmount)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);

            // 常规总金额
            orderDetail.setTotalAmount(totalAmountNYC.toPlainString());
            // 手工总金额/数量 = 手工单价
            if (StringUtils.isNotBlank(orderDetail.getManualTotalAmount())) {
                BigDecimal manualPrice = new BigDecimal(orderDetail.getManualTotalAmount())
                        .divide(new BigDecimal(orderDetail.getProductQuantity()), 2, RoundingMode.HALF_UP);
                orderDetail.setManualPrice(manualPrice.toPlainString());
            }
        }

        return Result.success(null);
    }

    private Map<String, PolicyPriceQueryRequest> queryGoodsDetailPrice(SalesOrderBizCreateRequest request) {
        PolicyPriceMainRequest priceMainRequest = convertPriceMainOrder(request);

        log.info("SalesOrderBizAssembleOfCostCenter#queryGoodsDetailPrice priceMainRequest: {}", priceMainRequest);
        List<PolicyPriceQueryRequest> policyPriceQueryRequests = normalPriceQueryUtils.queryPolicyPrice(priceMainRequest);
        log.info("SalesOrderBizAssembleOfCostCenter#queryGoodsDetailPrice policyPriceQueryRequests: {}", policyPriceQueryRequests);

        return Optional.ofNullable(policyPriceQueryRequests)
                .orElse(Lists.newArrayList())
                .stream()
                .collect(Collectors.toMap(o -> o.getMaterialCode() + "-" + o.getSalesUnitCode(), p -> p, (v1, v2) -> v1));
    }

    private PolicyPriceMainRequest convertPriceMainOrder(SalesOrderBizCreateRequest request) {
        log.info("=============convertMainOrder_request:" + JSON.toJSON(request));
        PolicyPriceMainRequest mainOrderInfo = new PolicyPriceMainRequest();
        mainOrderInfo.setFromSys(request.getFromSys());
        mainOrderInfo.setSalesOrganizationCode(request.getSalesOrganizationCode());
        mainOrderInfo.setBusinessType(request.getBusinessType());

        log.info("=============convertMainOrder_mainOrderInfo:" + JSON.toJSON(mainOrderInfo));
        mainOrderInfo.setCalculateItemList(convertPriceOrderLine(request.getOrderDetails(), request));
        return mainOrderInfo;
    }

    private List<PolicyPriceQueryRequest> convertPriceOrderLine(List<SalesOrderAtomCreateLineRequest> orderDetails, SalesOrderBizCreateRequest request) {
        if (CollectionUtils.isEmpty(orderDetails)) {
            return Lists.newArrayList();
        }

        String priceTypeCode = PriceTypeEnum.ZP01.getCode(); // 默认查询常规价
        if (OrderCategoryEnum.GROUP.getCode().equals(request.getOrderCategoryCode())) {
            priceTypeCode = PriceTypeEnum.ZMN1.getCode(); // 集团销售订单查询到岸价
        }

        List<PolicyPriceQueryRequest> responses = Lists.newArrayList();
        for (SalesOrderAtomCreateLineRequest orderLine : orderDetails) {
            if (StringUtils.isBlank(orderLine.getProductCode())) {
                continue;
            }
            PolicyPriceQueryRequest response = PolicyPriceQueryRequest.builder()
                    .priceTypeCode(priceTypeCode)
                    .orgSalesOrganizationCode(request.getSalesOrganizationCode())
                    .channelCode(request.getBusinessChannel())
                    .scItemGroupCode(request.getProductGroupCode())
                    .customerCode(request.getCustomerCode())
                    .customerSaleAddressCode(request.getCustomerCode())
                    .customerSendAddressCode(request.getShipToPartyCode())
                    .salesUnitCode(orderLine.getSalesUnitCode())
                    .materialCode(orderLine.getProductCode())
                    .departmentCode(request.getSalesDepartmentCode())
                    .factoryCode(orderLine.getDeliveryFactoryCode())
                    .storePlace(orderLine.getStockCode())
                    .build();
            responses.add(response);
        }
        return responses;
    }
}
